<?php
namespace app\admin\controller;
use think\Db;
class Sign extends Common
{

    /**签到每日记录列表
     * URL：admin/sign/dayList
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function dayList(){

        $this->assign('flag1',1);

        if (request()->isAjax()) {

            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));


//            教师关键字
            $keyword = input('post.keyword');
//            状态
            $status = input('post.status');
//            时间段
            $start_time = input('post.start_time');//起始时间
            $end_time   = input('post.end_time');//结束时间
//          当日时间
            $time1 = strtotime(date('Y-m-d'));
            $time2 = strtotime(date('Y-m-d',strtotime('+1 day')));

            if($start_time){
                $time1 = strtotime($start_time);
                if($end_time){
                    $time2   = strtotime($end_time)+24*60*60;
                }
                $time_where = "sr.sign_time >= $time1 AND sr.sign_time < $time2";
            }else{
                $time_where = "sr.sign_time >= $time1 AND sr.sign_time < $time2";
            }

            if($status){
                $map['sr.status'] =['like', $status];
            }

            $list = Db::name('teacher t')
                ->join('sign_recode sr','sr.teacher_id=t.id','left')
                ->join('section s','t.section_id=s.section_id','left')
                ->field('sr.*, t.teacher_no,t.true_name, s.title')
                ->where($map)
                ->where($time_where)
                ->where('t.true_name|t.teacher_no','like', "%" . $keyword . "%")
                ->order('sr.sign_time asc')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();

            if (!empty($list)) {
                foreach ($list['data'] as $k => $v) {
                    $list['data'][$k]['sign_time'] = toDate($v['sign_time']);
                    $teacher_id = $v['teacher_id'];
                    $list['data'][$k]['rule_name'] = Db("sign_rule")
                        ->where('person_type','like',"%\"$teacher_id\"%")->value('rule_name');
                }
            }


            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch('day_list');
    }


    /**签到每月记录列表
     * URL：admin/sign/monthList
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function monthList()
    {
        $this->assign('flag2',2);
        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            if(input('time')){
                $time = explode('-',input('time'));
            }else{
                $time = explode('-',date("Y-m",strtotime("-1 month")));
            }

            $list = Db::name('teacher t')
                ->join('sign_recode_month sr','t.id=sr.teacher_id','left')
                ->join('section s','t.section_id=s.section_id','left')
                ->field('sr.*, t.teacher_no,t.id as teacher_id , t.true_name, s.title')
                ->where('t.true_name|t.teacher_no','like',"%$keyword%")
                ->where('sr.month_time',$time[1])
                ->where('sr.year_time',$time[0])
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();


            foreach ($list['data'] as $k=>$v){
                $teacher_id = $v['teacher_id'];
                $list['data'][$k]['rule_name'] = Db("sign_rule")
                    ->where('person_type','like',"%\"$teacher_id\"%")->value('rule_name');
            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch('month_list');
    }

    /**一键生成上月签到报表
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function last_month_report(){
        if (request()->isAjax()) {

            //判断是否已存在上月签到报表
            $time = explode('-',date("Y-m",strtotime("-1 month")));
            $flag =  Db::name('sign_recode_month')->where('month_time',$time[1])->where('year_time',$time[0])->find();

            //查找未删除未禁用老师
            $teacher_list = Db::name('teacher')->where('is_del',0)->where('status',1)->select();

            //声明变量 所有老师的签到总计
            $all_sign_recode_data = [];

            //状态数组
            $status_arr = ['','normal_num', 'leave_num','','late_num','business_trip_num','absent_num'];

            //上个月的起始时间:
            $begin_time = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));
            $end_time = strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')));

            if($teacher_list){
                //遍历查找教师签到记录
                foreach ($teacher_list as  $k=>$v){

                    // 获取上月该老师所有签到记录
                    $sign_recode = Db::name('sign_recode')->field('status,count(*) as num')->where('teacher_id',$v['id'])->where('sign_time', ['>=',$begin_time],['<=',$end_time])
                        ->group('status')->having('count(status)')->select();

                    //应出勤
                    $actual_num = 0;

                    if($sign_recode){
                        foreach ($sign_recode as $key=>$val){

                            $teacher_sign_recode_data[$status_arr[$val['status']]] = $val['num'];

                            $actual_num = $actual_num + $val['num'];
                        }

                        //声明变量 该老师的签到总计
                        $teacher_sign_recode_data['teacher_id']         = $v['id'] ;
                        $teacher_sign_recode_data['actual_num']         = $actual_num;
                        $teacher_sign_recode_data['month_time']         = $time[1] ;
                        $teacher_sign_recode_data['year_time']          = $time[0] ;

                        //如果是更新拿到sign_recode_month表的教师记录id
                        if($flag){
                            $teacher_sign_recode_data['id']  = Db::name('sign_recode_month')->where('teacher_id',$v['id'])->where('month_time',$time[1])->where('year_time',$time[0])->value('id');
                            //进行数据更新
                            $re = Db::name('sign_recode_month')->where('id',$teacher_sign_recode_data['id'])->update($teacher_sign_recode_data);
                        }

                        //数据整理
                        $all_sign_recode_data[] = $teacher_sign_recode_data;

                    }

                }

            }


            if($flag){
            }else{
                //插入新数据
                $re = Db::name('sign_recode_month')->insertAll($all_sign_recode_data);
            }

            if($re){
                $this->success();
            }

            $this->error('生成失败');
        }
    }


    /**打卡接口
     * @param int $teacher_id
     * @param string $device_no
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function  punch_card($teacher_id=3,$device_no="21185a30-be91-402f-af4b-952ae7720a70"){
        $data = [
            'teacher_id' => $teacher_id,
            'device_no'  => $device_no,
            'sign_time'  => time()
        ];

        $last_recode = Db::name('sign_recode')->where('teacher_id',$teacher_id)
            ->where('sign_time','>=',strtotime(date('Y-m-d',time())))->find();
        if($last_recode){
            return json([
                'code'=>200,
                'msg' =>'今日已打卡'
            ]);
        }

        $re = Db::name('sign_recode')->insert($data);
        if($re){
            return json([
                'code'=>200,
                'msg' =>'success'
            ]);
        }
    }



    /**
     * 上午定时
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function am_timing()
    {

        $today_week = date("w");//今天周几
        $time1 = strtotime(date('Y-m-d'));//今天凌晨
        $time2 = strtotime(date("Y-m-d")) + 60 * 60 * 12;//今天中午12点
        $time = (strtotime(date("Y-m-d"))+60*60*12)-1;//今天中午12点

        //上午签到
        $rule = Db::name('sign_rule')
            ->where('is_del', 0)
            ->where('work_time', 'like', "%$today_week%")
            ->where('use_time_type', 1)
            ->select();

        foreach ($rule as $k => $v) {

            if ($v['use_time_type'] === 1) {
                $flag = false;
                //根据星期判断
                if ($v['work_time']) {
                    $rule[$k]['work_time'] = unserialize($v['work_time']);
                    if (in_array($today_week, $rule[$k]['work_time'])) {
                        $flag = true;
                    }
                }

                //是否放假
                if ($rule[$k]['sub_workday']) {
                    $rule[$k]['sub_workday'] = unserialize($v['sub_workday']);
                    foreach ($rule[$k]['sub_workday'] as $key => $val) {
                        $rule[$k]['sub_workday'][$key] = $sub_work = explode('/', $val);
                        $start_time = strtotime($sub_work[0]);
                        $end_time = strtotime($sub_work[1]) + 86400;
                        if ($time <= $end_time && $time >= $start_time) {
                            $flag = false;
                        }
                    }
                }

                //是否加班
                if ($rule[$k]['add_workday']) {
                    $rule[$k]['add_workday'] = unserialize($v['add_workday']);
                    foreach ($rule[$k]['add_workday'] as $key => $val) {
                        $rule[$k]['add_workday'][$key] = $add_workday = explode('/', $val);
                        $start_time = strtotime($add_workday[0]);
                        $end_time = strtotime($add_workday[1]) + 86400;
                        if ($time <= $end_time && $time >= $start_time) {
                            $flag = true;

                        }
                    }
                }

                if ($flag) {
                    $data = [
                        'sign_rule_id' => $rule[$k]['id'],
                        'status' => 6,//旷工
                        'sign_time' => $time
                    ];
                    //已签到的
                    $teacher_ids = Db::name('sign_recode')->where('sign_time', ['>', $time1], ['<=', $time2], 'and')->field('id,teacher_id')->select();

                    if ($rule[$k]['person_type']) {
                        $rule[$k]['person_type'] = unserialize($v['person_type']);
                        if ($teacher_ids){

                            foreach ($teacher_ids as $k1 => $v1) {

                                if (in_array($v1['teacher_id'], $rule[$k]['person_type'])) {

                                    $start_time = date("Y-m-d",time())." ".$rule[$k]['start_time'];
                                    $end_time = date("Y-m-d",time())." ".$rule[$k]['end_time'];
                                    $late_max_time = date("Y-m-d",time())." ".$rule[$k]['late_max_time'];
                                    $data1['section_id'] = Db::name('teacher')->where('id', $v1['teacher_id'])->value('section_id');
                                    $data1['sign_rule_id']=$rule[$k]['id'];
                                    if (strtotime($start_time)<=$v1['sign_time'] && strtotime($end_time)>=$v1['sign_time']){
                                        //正常
                                        $data1['status'] =1;
                                        Db::name('sign_recode')->where('id',$v1['id'])->update($data1);
                                    }elseif (strtotime($end_time)<$v1['sign_time'] && strtotime($late_max_time)>=$v1['sign_time']){
                                        //迟到
                                        $data1['status'] =4;
                                        $data1['late_time'] = (strtotime($late_max_time)-$v1['sign_time'])/60;
                                        Db::name('sign_recode')->where('id',$v1['id'])->update($data1);
                                    }else{
                                        //旷工
                                        $data1['status'] =6;
                                        Db::name('sign_recode')->where('id',$v1['id'])->update($data1);
                                    }

                                    //返回包含数组中所有键名的一个新数组
                                    $kk = array_keys($rule[$k]['person_type'], $v1['teacher_id'] . '');
                                    unset($rule[$k]['person_type'][$kk[0]]);
                                }
                            }
                            if ($rule[$k]['person_type']){
                                foreach ($rule[$k]['person_type'] as $k2 => $v2) {
                                    $data['section_id'] = Db::name('teacher')->where('id', $v2)->value('section_id');
                                    $data['teacher_id'] = $v2;
                                    $data['device_no'] = "a无1";
                                    Db::name('sign_recode')->insert($data);
                                }
                            }
                            $this->success('同步成功');
                        }else{

                            foreach ($rule[$k]['person_type'] as $k3 =>$v3){
                                $data['section_id'] = Db::name('teacher')->where('id', $v3)->value('section_id');
                                $data['teacher_id'] = $v3;
                                $data['device_no'] = "a无2";
                                Db::name('sign_recode')->insert($data);
                            }
                            $this->success('同步成功');
                        }
                    }

                }
            }

        }

    }

    /**
     * 下午定时
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function pm_timing()
    {

        $today_week = date("w");//今天周几
        $time2 = strtotime(date("Y-m-d"))+60*60*12;//今天中午12点
        $time3 = strtotime(date("Y-m-d"))+60*60*18;//今天下午18点
        $time=(strtotime(date("Y-m-d"))+60*60*18)-1;//现在时间

        //下午签到
        $rule = Db::name('sign_rule')
            ->where('is_del',0)
            ->where('work_time','like',"%$today_week%")
            ->where('use_time_type',2)
            ->select();

        foreach ($rule as $k=>$v){

            if ($v['use_time_type']==2){
                $flag=false;
                //根据星期判断
                if($v['work_time']){
                    $rule[$k]['work_time']=unserialize($v['work_time']);
                    if(in_array($today_week, $rule[$k]['work_time'])){
                        $flag=true;
                    }
                }

                //是否放假
                if ($rule[$k]['sub_workday']){
                    $rule[$k]['sub_workday']=unserialize($v['sub_workday']);
                    foreach ($rule[$k]['sub_workday'] as $key=>$val){
                        $rule[$k]['sub_workday'][$key]=$sub_work=explode('/',$val);
                        $start_time=strtotime($sub_work[0]);
                        $end_time=strtotime($sub_work[1])+86400;
                        if($time<=$end_time&&$time>=$start_time){
                            $flag=false;
                        }
                    }
                }

                //是否加班
                if($rule[$k]['add_workday']){
                    $rule[$k]['add_workday']=unserialize($v['add_workday']);
                    foreach ($rule[$k]['add_workday'] as $key=>$val){
                        $rule[$k]['add_workday'][$key]=$add_workday= explode('/',$val);
                        $start_time=strtotime($add_workday[0]);
                        $end_time=strtotime($add_workday[1])+86400;
                        if($time<=$end_time&&$time>=$start_time){
                            $flag=true;
                        }
                    }
                }

                if ($flag) {
                    $data = [
                        'sign_rule_id' => $rule[$k]['id'],
                        'status' => 6,//旷工
                        'sign_time' => $time
                    ];
                    //已签到的
                    $teacher_ids = Db::name('sign_recode')->where('sign_time', ['>', $time2], ['<=', $time3], 'and')->field('id,teacher_id')->select();

                    if ($rule[$k]['person_type']) {
                        $rule[$k]['person_type'] = unserialize($v['person_type']);
                        if ($teacher_ids){

                            foreach ($teacher_ids as $k1 => $v1) {

                                if (in_array($v1['teacher_id'], $rule[$k]['person_type'])) {

                                    $start_time = date("Y-m-d",time())." ".$rule[$k]['start_time'];
                                    $end_time = date("Y-m-d",time())." ".$rule[$k]['end_time'];
                                    $late_max_time = date("Y-m-d",time())." ".$rule[$k]['late_max_time'];
                                    $data1['section_id'] = Db::name('teacher')->where('id', $v1['teacher_id'])->value('section_id');
                                    $data1['sign_rule_id']=$rule[$k]['id'];
                                    if (strtotime($start_time)<=$v1['sign_time'] && strtotime($end_time)>=$v1['sign_time']){
                                        //正常
                                        $data1['status'] =1;
                                        Db::name('sign_recode')->where('id',$v1['id'])->update($data1);
                                    }elseif (strtotime($end_time)<$v1['sign_time'] && strtotime($late_max_time)>=$v1['sign_time']){
                                        //迟到
                                        $data1['status'] =4;
                                        $data1['late_time'] = (strtotime($late_max_time)-$v1['sign_time'])/60;
                                        Db::name('sign_recode')->where('id',$v1['id'])->update($data1);
                                    }else{
                                        //旷工
                                        $data1['status'] =6;
                                        Db::name('sign_recode')->where('id',$v1['id'])->update($data1);
                                    }

                                    //返回包含数组中所有键名的一个新数组
                                    $kk = array_keys($rule[$k]['person_type'], $v1['teacher_id'] . '');
                                    unset($rule[$k]['person_type'][$kk[0]]);
                                }
                            }
                            if ($rule[$k]['person_type']){
                                foreach ($rule[$k]['person_type'] as $k2 => $v2) {
                                    $data['section_id'] = Db::name('teacher')->where('id', $v2)->value('section_id');
                                    $data['teacher_id'] = $v2;
                                    $data['device_no'] = "p无1";
                                    Db::name('sign_recode')->insert($data);
                                }
                            }
                            $this->success('同步成功');
                        }else{

                            foreach ($rule[$k]['person_type'] as $k3 =>$v3){
                                $data['section_id'] = Db::name('teacher')->where('id', $v3)->value('section_id');
                                $data['teacher_id'] = $v3;
                                $data['device_no'] = "p无2";
                                Db::name('sign_recode')->insert($data);
                            }
                            $this->success('同步成功');
                        }
                    }

                }
            }
        }

    }

}